<!-- 定点消息类型 -->
<template>
  <div class="temp-container">
    <!-- 消息名称 -->
    <el-form
      :model="submitParams"
      ref="submitParams"
      label-width="100px"
      :rules="rules"
    >
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="col_title">消息名称</span>
        </div>
        <el-form-item label="消息名称" prop="name">
          <el-input
            class="common-left"
            v-model="submitParams.name"
            maxlength="32"
            show-word-limit
            style="width:80%"
          ></el-input>
        </el-form-item>
      </el-card>
      <!-- 导入用户和内容 -->
      <el-card class="box-card" customClass="customClass">
        <div slot="header" class="clearfix">
          <span class="col_title">导入用户和内容</span>
        </div>
        <el-form-item label="选择方式" prop="userType">
          <el-radio-group
            v-model="submitParams.configData.studentConfig.importType"
            class="common-left"
            @change="getRadioValue"
          >
            <el-radio
              :disabled="radioDisabled"
              :label="item.label"
              v-for="(item, index) in selectType"
              :key="index"
              >{{ item.value }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="userDataNum">
          <div class="totalNum common-left">
            <span> 共{{ submitParams.userDataNum }}人 </span>
            <span> 共{{ submitParams.userDataNum }}条内容 </span>
            <span @click="handleImport" class="batch"> +批量导入 </span>
            <span @click="clearAll" class="clearAll"> -全部清空 </span>
          </div>
          <div class="common-left tips">
            <div
              style="display:grid; grid-template-columns: 40px 500px;grid-template-rows: 100px;"
            >
              <div style="line-height:20px!important">
                说明:
              </div>
              <div>
                <div style="line-height:20px!important">
                  内容字数不可大于300，短信70字以内按一条收费，大于70字按67字一条收费。
                </div>
                <div style="line-height:20px!important">
                  消息发送时会做发送号码和发送内容的去重，最终发送人数以详情页的【发送数量】为准；
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-card>
      <!-- 发送渠道 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="col_title">发送渠道</span>
        </div>
        <el-form-item label="选择渠道" prop="copyMessageChannels">
          <el-checkbox-group
            v-model="submitParams.copyMessageChannels"
            class="common-left"
          >
            <el-checkbox
              :disabled="
                submitParams.configData.studentConfig.importType ===
                  'PHONE_CONTENT' && item.label === 'NOTICE'
              "
              :label="item.label"
              v-for="(item, index) in channelList"
              :key="index"
              >{{ item.value }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-card>
      <!-- 发送时间 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="col_title">发送时间</span>
        </div>
        <el-form-item label="选择时间" prop="sendTimeType">
          <el-radio-group
            v-model="submitParams.configData.sendTimeType"
            class="form-item"
            @change="sendTimeTypeChange"
          >
            <el-radio label="SEND_IMMEDIATELY">立即发送</el-radio>
            <el-radio label="TIMED_SENDING" class="send-time"
              >定时发送</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          prop="configData.sendTime"
          v-show="submitParams.configData.sendTimeType == 'TIMED_SENDING'"
        >
          <el-date-picker
            v-model="submitParams.configData.sendTime"
            type="datetime"
            size="small"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            class="form-item"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <div class="row_center">
          <el-button type="success" @click="saveTemp" v-if="!$route.query.id"
            >保存</el-button
          >
          <el-button type="success" @click="complie" v-if="$route.query.id"
            >编辑</el-button
          >
          <el-button type="info" @click="cancle">取消</el-button>
        </div>
      </el-card>
    </el-form>
    <importUsersAndContent :params="params" />
  </div>
</template>

<script>
import {
  createFixedMessage,
  templateData,
  complieFixedMessage
} from '@/api/notice'
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { clearTagMixins } from '@/mixins/clearTag'
import importUsersAndContent from '@/components/messageManagement/template/importUsersAndContent' // 学院分组弹窗

export default {
  name: 'operationTemplate',
  mixins: [clearTagMixins],
  data() {
    var userDataNum = (rule, value, callback) => {
      value === 0 ? callback(new Error('请导入用户和内容')) : callback()
    }
    var sendTime = (rule, value, callback) => {
      let chouseType = this.submitParams.configData.sendTimeType
      let chouseTime = this.submitParams.configData.sendTime
      if (chouseType === 'TIMED_SENDING' && !chouseTime) {
        callback(new Error('请选择时间'))
      } else {
        callback()
      }
    }
    return {
      radioDisabled: false,
      pickerOptions: {
        disabledDate(time) {
          //此条为设置禁止用户选择今天之前的日期，包含今天。
          // return time.getTime() <= (Date.now());
          //此条为设置禁止用户选择今天之前的日期，不包含今天。
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        messageChannels: [
          { required: true, message: '请选择渠道', trigger: 'change' }
        ],
        copyMessageChannels: [
          { required: true, message: '请选择渠道', trigger: 'change' }
        ],
        userDataNum: [
          {
            required: true,
            validator: userDataNum,
            trigger: ['change', 'blur']
          }
        ],
        'configData.sendTime': [
          {
            required: true,
            validator: sendTime,
            message: '请选择时间',
            trigger: 'change'
          }
        ]
      },
      selectType: [
        { label: 'ACCOUNT_CONTENT', value: '大鹏号和内容方式导入' },
        { label: 'PHONE_CONTENT', value: '手机号和内容方式导入' }
      ],
      channelList: [
        { label: 'SMS', value: '短信' },
        { label: 'NOTICE', value: '站内信' }
      ],
      choseLoad: [],
      params: {
        centerDialogVisible: false,
        title: '',
        importType: ''
      },
      submitParams: {
        configData: {
          sendTime: '',
          sendTimeType: 'SEND_IMMEDIATELY',
          studentConfig: {
            userRange: 'TARGETED',
            importType: 'ACCOUNT_CONTENT'
          },
          userType: 'STUDENT'
        },
        messageChannels: [],
        copyMessageChannels: [],
        userDataNum: 0,
        messageTemplateAlias: 'TARGETED_MESSAGE_TEMPLATE',
        name: '',
        userDataId: ''
      }
    }
  },
  components: {
    importUsersAndContent
  },
  created() {
    if (this.$route.query.id) {
      let params = {}
      templateData(
        this.$route.query.id,
        (res) => {
          let { name, configData, messageTemplateAlias, userDataNum } = res
          this.submitParams.name = name
          this.submitParams.configData = configData
          this.submitParams.userDataNum = userDataNum
          delete this.submitParams.configData.consultantConfig
          this.submitParams.messageTemplateAlias = messageTemplateAlias
          this.submitParams.copyMessageChannels = res.messageChannels.map(
            (item) => {
              return item.type
            }
          )
        },
        (err) => {
          this.$message({ message: err.message, type: 'warning' })
        }
      )
    }
  },
  async mounted() {},
  watch: {
    'submitParams.copyMessageChannels': {
      handler(newV, oldV) {
        if (newV.length > 0) {
          this.submitParams.messageChannels = []
          newV.forEach((item) => {
            let obj = {}
            obj.type = item
            this.submitParams.messageChannels.push(obj)
          })
        }
      }
    },
    'submitParams.userDataId': {
      handler(newV, oldV) {
        if (newV) {
          this.radioDisabled = true
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    getRadioValue(val) {
      if (this.submitParams.copyMessageChannels) {
        this.submitParams.copyMessageChannels = []
      }
    },
    complie() {
      this.$refs['submitParams'].validate((valid) => {
        if (valid) {
          let params = { ...this.submitParams }
          delete params.copyMessageChannels
          delete params.userDataNum
          complieFixedMessage(
            this.$route.query.id,
            params,
            (res) => {
              this.$message({ message: '修改成功', type: 'success' })
              this.clearTag()
            },
            (err) => {
              this.$message({ message: err.message, type: 'warning' })
            }
          )
        }
      })
    },
    // 取消
    cancle() {
      this.clearTag()
    },
    /*退出*/
    signOut() {
      this.$router.go(-1)
    },
    // 全部清空
    clearAll() {
      this.submitParams.userDataNum = 0
      this.submitParams.userDataId = ''
      this.radioDisabled = false
    },

    async saveTemp() {
      this.$refs['submitParams'].validate((valid) => {
        if (valid) {
          let params = { ...this.submitParams }
          delete params.copyMessageChannels
          delete params.userDataNum
          createFixedMessage(
            params,
            (res) => {
              this.$message({ message: '创建成功', type: 'success' })
              this.clearTag()
            },
            (err) => {
              this.$message({ message: err.message, type: 'warning' })
            }
          )
        }
      })
    },

    handleImport() {
      let { importType } = this.submitParams.configData.studentConfig
      this.params.centerDialogVisible = true
      importType === 'ACCOUNT_CONTENT'
        ? ((this.params.title = '大鹏号和内容'),
          (this.params.importType = 'ACCOUNT_CONTENT'))
        : ((this.params.title = '手机号和内容'),
          (this.params.importType = 'PHONE_CONTENT'))
    },

    sendTimeTypeChange(val) {
      if (val === 'SEND_IMMEDIATELY') {
        this.submitParams.configData.sendTime = ''
        this.$refs['submitParams'].clearValidate('configData.sendTime')
      } else if (val === 'TIMED_SENDING') {
        this.submitParams.configData.sendTime = ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
.tips {
  font-size: 12px;
  margin-top: 30px;
}
:deep(.common-left) {
  margin-left: 100px !important;
}
.customClass {
  color: #f56c6c;
  font-size: 20px;
}
.el-card .header {
  border: 2px solid red;
}
:deep(.el-form-item__label) {
  color: #333333 !important;
  font-weight: 400;
}
:deep(.el-form-item__label) {
  display: flex !important;
  justify-content: flex-start !important;
}
:deep(.el-form-item__label) {
  color: #333333 !important;
  font-weight: 400;
}
:deep(.el-form-item__error) {
  margin-left: 100px;
}
:deep(.el-form-item__content) {
  margin-left: 200px;
}
:deep(.el-form-item__error) {
  margin-left: 100px;
}
:deep(.el-button--text) {
  color: #03be91 !important;
}
:deep(.el-message-box) {
  width: 820px !important;
}
:deep(.el-button--primary) {
  background: #03be91 !important;
  border-color: #68cab3 !important;
}
.col_title {
  color: rgb(51, 51, 51);
  font-size: 20px;
  font-weight: 700;
}
.mt_10 {
  margin-top: 10px;
}
.col {
  display: flex !important;
  flex-direction: column !important;
}
.row_center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.clearAll {
  cursor: pointer;
  width: 100px;
  height: 30px;
  color: white;
  background: rgba(29, 200, 164, 1);
  display: flex;
  justify-content: center;
  align-items: center;
}
.batch {
  cursor: pointer;
  width: 100px;
  height: 30px;
  color: white;
  background: rgba(29, 200, 164, 1);
  display: flex;
  justify-content: center;
  align-items: center;
}
.totalNum {
  display: flex;
  width: 400px;
  justify-content: space-between;
  align-items: center;
}
/*学员分组样式*/
.studentGrouping {
  display: flex;
  margin-left: 100px;
  width: 600px;
  flex-direction: column;
  justify-content: space-around;
  &__btn {
    display: flex;
    flex-direction: row;
  }
}
.table-box {
  margin-top: 20px;
}
.view-total {
  color: #03af81;
  width: 100px;
  margin-left: 100px;
  cursor: pointer;
}
.temp-container {
  display: grid;
  grid-template-columns: repeat(100%);
  .table {
    width: 500px;
    height: 100px;
    td th {
      text-align: center;
    }
  }
}
.form-item {
  margin-left: 100px;
}
.channel-wrap {
  margin-left: 90px;
  & > p {
    margin: 0 0 0 10px;
    color: red;
  }
  .channel-checkbox {
    margin-left: 10px;
    border-bottom: #03af81 solid 2px;
  }
}
.userinfo-btn {
  margin-left: 10px;
}
.header-tip {
  float: right;
}
.channel-content {
  margin-left: 100px;
  .channel-content_label {
    margin-right: 20px;
    width: 100px;
    text-align: left;
    display: block;
    float: left;
  }
  .label-student:before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }
}
</style>
